﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebAsp.DTO;

namespace WebAsp.DAL
{
    public class NewsDAL
    {
        public NewsDAL()
        { 
        }

        public static List<NewsDTO> GetList()
        {
            LinQDataContext dt = new LinQDataContext();
            var query = from t in dt.newsGetList()
                        select new NewsDTO(t.NewsID, t.Title, t.Summary.ToString(), t.Contents, t.ImagesLink, t.Name);
            return query.ToList();
        }

        public static List<NewsDTO> GetListByCategory(int catID)
        {
            LinQDataContext dt = new LinQDataContext();
            var query = from t in dt.newsGetListByCategory(catID)
                        select new NewsDTO(t.NewsID, t.Title, t.Summary.ToString(), t.Contents, t.ImagesLink, t.Name);
            return query.ToList();
        }

        public static NewsDTO GetItem(int ID)
        {
            LinQDataContext dt = new LinQDataContext();
            var query = from t in dt.newsGetItem(ID)
                        select new NewsDTO(t.NewsID, t.Title, t.Summary.ToString(), t.Contents, t.ImagesLink, t.Name);
            return query.FirstOrDefault();
        }

        public static void Insert(NewsDTO item)
        {
            LinQDataContext dt = new LinQDataContext();
            NEW newsItem = new NEW();
            newsItem.Title = item.Title;
            newsItem.Summary = item.Summary;
            newsItem.Contents = item.Contents;
            newsItem.ImagesLink = item.ImagesLink;
            newsItem.CategoryID = item.CategoryID;
            dt.NEWs.InsertOnSubmit(newsItem);
            dt.SubmitChanges();
        }

        public static void Update(NewsDTO item)
        {
            LinQDataContext dt = new LinQDataContext();
            NEW newsItem = dt.NEWs.Single(p => p.NewsID == item.ID);
            newsItem.Title = item.Title;
            newsItem.Summary = item.Summary;
            newsItem.Contents = item.Contents;
            newsItem.ImagesLink = item.ImagesLink;
            newsItem.CategoryID = item.CategoryID;
            dt.SubmitChanges();
        }

        public static void Delete(int ID)
        {
            LinQDataContext dt = new LinQDataContext();
            NEW newsItem = dt.NEWs.Single(p => p.NewsID == ID);
            dt.NEWs.DeleteOnSubmit(newsItem);
            dt.SubmitChanges();
        }
    }
}